package com.example.note.util;



import java.util.Timer;
import java.util.TimerTask;

public class HeartBeatGenerator extends HeartBeatGeneratorAbstract {

    private Timer timer = null;
	private BeatAble heart;
	private int prepare;
	private int delay;
	private HeartBeatListener listener = null;
	
	public HeartBeatListener getListener()
	{
		return listener;
	}

	public void setListener(HeartBeatListener listener)
	{
		this.listener = listener;
	}

	public HeartBeatGenerator(BeatAble heart, int prepare, int delay){
		this.heart = heart;
		this.prepare = prepare;
		this.delay = delay;
	}
	
    class beatTask extends TimerTask{
        BeatAble heart;
        Timer timer;

        public beatTask(BeatAble heart,Timer timer){
            this.heart = heart;
            this.timer = timer;
        }

        @Override
        public void run() {
        	if(listener != null){
        		listener.OnBeat(heart,timer);
        	}
            heart.beat();
            if(!heart.isStillBeat()){
                stopBeat();
            }
        }
    }


    @Override
    public void startBeat() {
        timer = new Timer();
        timer.schedule(new beatTask(heart,timer),prepare,delay);
    }

    @Override
    public void stopBeat() {
        timer.cancel();
        timer = null;
    }

	@Override
	public Timer geTimer() {
		// TODO Auto-generated method stub
		return timer;
	}

	@Override
	public boolean isStillBeat()
	{
		// TODO Auto-generated method stub
		return (timer == null)?false:true;
	}
}
